package com.zhang.study.chapter03;

import com.zhang.study.chapter03.node.Node;

import java.util.ArrayList;
import java.util.List;

import static com.zhang.util.NodeUtil.*;

/**
 * @author zhang
 * 翻转链表
 */
public class Code01_ReverseList {


    /**
     * 翻转链表
     *
     * @param head 头节点
     * @return 翻转后链表的头结点
     */
    public static Node reverseLinkedList(Node head) {
       if(head==null){
           return null;
       }
       Node pre = null;
       Node next = null;
       while (head!=null){
           next = head.next;
           head.next = pre;
           pre = head;
           head = next;
       }
        return pre;
    }

    /**
     * 测试
     * @param head 头结点
     * @return 翻转后链表的头结点
     */
    public static Node testReverseLinkedList(Node head) {
        if (head == null) {
            return null;
        }
        ArrayList<Node> list = new ArrayList<>();
        while (head != null) {
            list.add(head);
            head = head.next;
        }
        list.get(0).next = null;
        int N = list.size();
        for (int i = 1; i < N; i++) {
            list.get(i).next = list.get(i - 1);
        }
        return list.get(N - 1);
    }

    public static void main(String[] args) {
        int len = 50;
        int value = 100;
        int testTime = 100000;
        System.out.println("test begin!");
        for (int i = 0; i < testTime; i++) {
            // 生成链表头结点
            Node node1 = generateRandomLinkedList(len, value);
            // 链表头结点值 list
            List<Integer> list1 = getLinkedListOriginOrder(node1);
            // 翻转后的头结点
            node1 = reverseLinkedList(node1);
            if (!checkLinkedListReverse(list1, node1)) {
                System.out.println("Oops1!");
            }

            Node node2 = generateRandomLinkedList(len, value);
            List<Integer> list2 = getLinkedListOriginOrder(node2);
            node2 = testReverseLinkedList(node2);
            if (!checkLinkedListReverse(list2, node2)) {
                System.out.println("Oops2!");
            }

        }
        System.out.println("test finish!");
    }

}
